package dbutil;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

public class DBUtils {

	public static Object[] getRowData(ResultSet resultSet) throws SQLException {
		ResultSetMetaData rsMeta = resultSet.getMetaData();
		int columnCount = rsMeta.getColumnCount();
		Object rowData[] = new Object[columnCount];
		for (int colIndex = 1; colIndex <= columnCount; colIndex++) {
			rowData[colIndex - 1] = resultSet.getObject(colIndex);
		}
		return rowData;
	}

	public static String[] getColumnNames(ResultSet resultSet)
			throws SQLException {
		ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
		int columnCount = resultSetMetaData.getColumnCount();
		String columnNames[] = new String[columnCount];
		for (int colIndex = 1; colIndex <= columnCount; colIndex++) {
			columnNames[colIndex - 1] = resultSetMetaData
					.getColumnName(colIndex);
		}

		return columnNames;
	}

	public static ArrayList<HashMap<String, Object>> putDataIntoList(
			ResultSet resultSet) {
		ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
		try {
			while (resultSet.next()) {
				Object[] data = getRowData(resultSet);
				String[] columnName = getColumnNames(resultSet);
				HashMap<String, Object> map = new HashMap<String, Object>();
				for (int i = 0; i < columnName.length; i++) {
					map.put(columnName[i], data[i]);
				}
				listData.add(map);
			}
		} catch (SQLException ex) {

		}
		return listData;
	}

	public static int deleteData(String tableName, String column, String value) {
		ConnectDB.connectDB();
		String SQL = "DELETE FROM " + tableName + " WHERE " + column + "='"
				+ value + "'";
		int numberRowsDeleted = -1;
		try {
			numberRowsDeleted = ConnectDB.statement.executeUpdate(SQL);
		} catch (SQLException se) {
			System.out.println(" SQL is invalid");
			se.printStackTrace();
		}

		return numberRowsDeleted;

	}

}
